<template>
  <view>
    <u-navbar title="动态详情" fixed placeholder autoBack></u-navbar>
    <view class="content">
      <z-paging ref="paging" style="top: calc(var(--status-bar-height) + 44px);height: calc(100% - 104px);" fixed 
      use-safe-area-placeholder refresher-vibrate refresher-background="#ffffff" refresher-only
			@query="onRefresh" safe-area-inset-bottom show-refresher-when-reload show-refresher-update-time @scroll="onScroll">
        <template #refresher="{refresherStatus}">
					<c-custom-refresher :status="refresherStatus" />
				</template>
        <u-gap height="10px" bgColor="#f5f5f5"></u-gap>
        <view class="body">
          <view class="user">
            <view class="avatar">
              <u-avatar :src="fileUrl + item.avatar" :size="48"></u-avatar>
            </view>
            <view class="name">
              <view class="name_label">{{ item.author }}</view>
              <view style="color: #888;font-size: 12px;display: flex;align-items: center;">
                <text>{{ item.createTime }}</text>
                <text style="display: block;width: 1px;height: 12px;background-color: #ccc;margin: 0 8px;"></text>
                <text>{{ item.clazz }}</text>
              </view>
            </view>
          </view>
          <view class="article">
            <u-parse :content="item.content"></u-parse>
          </view>
          <c-album-list :urls="item.images" :multipleSize="multipleSize" :space="10"></c-album-list>
          <view style="height: 20px;"></view>
          <u-gap height="10" bgColor="#f5f5f5"></u-gap>
          <view class="album__footer">
            <view>
              <image src="/static/tab2/icon_views.png"></image>
              <text>{{ item.views }}</text>
            </view>
            <view>
              <image src="/static/tab2/icon_comments.png"></image>
              <text>{{ item.comments }}</text>
            </view>
            <view @click="handleLikes(item)">
              <c-likes :liked="item.liked"></c-likes>
              <text>{{ item.likes }}</text>
            </view>
          </view>
        </view>
        <view class="comments">
          <view class="comment_title">
            评论({{ total }})
          </view>
          <view class="comment_content" v-if="total != 0">
            <view class="content-item" v-for="(item, index) in commentList" :key="index">
              <view class="user">
                <view class="user_avatar">
                  <u-avatar :src="fileUrl + item.avatar" :size="48"></u-avatar>
                </view>
                <view class="user_info">
                  <view class="user_name">
                    <view class="user_name_label">{{ item.nickname }}</view>
                    <view class="user_name_tag" v-if="item.userId == $store.getters.id">我</view>
                  </view>
                  <view class="comment-property">
                    <text>{{ item.time }}</text>
                  </view>
                </view>
              </view>
              <view class="item_content">{{ item.content }}</view>
              <view class="user_ip">
                <view>发表于{{ item.ip }}</view>
                <u-icon name="more-dot-fill" @click="moreAction(item, item.userId == $store.getters.id)"></u-icon>
              </view>
            </view>
            <u-loadmore :status="loadMore" nomoreText="已经到底啦" :marginTop="20" :marginBottom="20" />
          </view>
          <view v-else>
            <u-empty :icon="require('@/static/no_comments.png')" :marginTop="30" noneText></u-empty>
          </view>
        </view>
      </z-paging>
      <view class="comment_send">
        <u-textarea v-model="comment" placeholder="请输入你想评论的内容" :autoHeight="autoHeight" :height="height" 
        @linechange="lineChange"></u-textarea>
        <view class="button" @click="handleSend">发送</view>
      </view>
    </view>
    <u-action-sheet :actions="actions" cancel-text="取消" safeAreaInsetBottom
    :show="show" @close="show = false" @select="handleAction"></u-action-sheet>
    
    <c-loading></c-loading>
  </view>
</template>

<script>
import {
  forumDetail,
  getForumComment,
  addForumComment,
  delComment,
  plusViews,
  forumLikes
} from '@/api/forum'
import { dateFormat } from '@/utils/date'
export default {
  data() {
    return {
      fid: '',
      item: {
        avatar: '',
        clazz: '',
        author: '',
        images: [],
        createTime: ''
      },
      commentList: [],
      multipleSize: 70,
      height: 25,
      autoHeight: true,
      comment: '',
      current: 1,
      total: 0,
      loadMore: 'loadmore',
      show: false,
      actions: [],
      commentItem: {},
    }
  },
  methods: {
    getDetail() {
      forumDetail(this.fid, this.$store.getters.id).then(res => {
        if(res.code === 200) {
          const images = []
          JSON.parse(res.data.images).forEach(img => {
            images.push(this.fileUrl + img)
          })
          res.data.images = images
          this.item = res.data
          this.item.createTime = dateFormat(this.item.createTime)
        }
        this.$refs.paging.complete()
      })
    },
    getCommentList(isRefresh) {
      const params = {}
      params.current = this.current
      params.id = this.fid
      getForumComment(params).then(res => {
        if(res.code === 200) {
          if(isRefresh) {
            this.commentList = []
          }
          this.total = res.data.total
          res.data.list.forEach(item => {
            item.time = dateFormat(item.time)
            this.commentList.push(item)
          })
          if(res.data.total > this.commentList.length) {
            this.loadMore = 'loadmore'
          }else {
            this.loadMore = 'nomore'
          }
        }
        this.isRequest = false
        this.$refs.paging.complete()
      }).catch(err => {
        this.isRequest = false
        this.$refs.paging.complete()
      })
    },
    onRefresh(current, size) {
      this.current = current
      this.getCommentList(true)
    },
    lineChange(e) {
      if(e.target.lineCount >= 4) {
        this.autoHeight = false
        this.height = 84
      }else {
        this.autoHeight = true
        this.height = e.target.height
      }
    },
    handleSend() {
      // #ifdef APP
      uni.getLocation({
        type: 'wgs84',
        geocode: true,
        isHighAccuracy: true,
        success: ({ longitude, latitude, address }) => {
          this.commentMethod(address.province + address.city, longitude + ',' + latitude)
        },
        fail: (error) => {
          this.$toast.show({
            msg: '评论失败'
          })
        }
      })
      // #endif
      // #ifdef H5
      uni.request({
        url: `https://restapi.amap.com/v3/ip?key=9a6012990ac5a512d7a40dd9be1e0237`,
        method: 'GET',
        success: ({ data, statusCode, header }) => {
          if(data.status == 1) {
            this.commentMethod(data.province + data.city, '')
          }else {
            this.$toast.show({
              msg: '评论失败'
            })
          }
        },
        fail: () => {
          this.$toast.show({
            msg: '评论失败'
          })
        }
      })
      // #endif
    },
    commentMethod(ip, lngLat) {
      const params = {}
      params.forumId = this.fid
      params.userId = this.$store.getters.id
      params.comment = this.comment
      params.ip = ip
      params.lngLat = lngLat
      addForumComment(params).then(res => {
        if(res.code === 200) {
          this.getCommentList(true)
          this.comment = ''
          this.$toast.show({
            msg: '评论成功'
          })
        }
      })
    },
    onLoadMore() {
      if(!this.isRequest) {
        this.isRequest = true
        this.current++
        this.getCommentList(false)
      }
    },
    onScroll(e) {
      const { deltaY, scrollTop, scrollHeight } = e.target
      if(deltaY < 0 && scrollHeight - this.contentHeight - scrollTop < 50 && this.loadMore == 'loadmore') {  //向下滑动
        this.timer && clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.loadMore = 'loading'
          this.onLoadMore()
        }, 300)
      }
    },
    moreAction(item, isMy) {
      this.commentItem = item
      if(isMy) {
        this.actions = [ { name: '删除', index: '0', icon: 'trash' } ]
      }else {
        this.actions = [ { name: '举报', index: '1', icon: 'error' } ]
      }
      this.show = true
      // uni.showActionSheet({
      //   itemList: ['删除'],
      //   success: ({ tapIndex }) => {
      //     console.log(tapIndex);
      //   },
      //   fail: (error) => {}
      // })
    },
    handleAction({ index }) {
      if(index == '0') {
        delComment(this.commentItem.id).then(res => {
          if(res.code === 200) {
            this.getCommentList(true)
          }
          this.$toast.show({
            msg: res.msg
          })
        })
      }else if(index == '1') {
        uni.navigateTo({
          url: `/pages/report/index?uid=${this.commentItem.userId}`
        })
      }
    },
    handleLikes(item) {
      forumLikes(item.id, this.$store.getters.id).then(res => {
        if(res.code === 200) {
          this.$toast.show({
            msg: res.msg
          })
          if(res.data) {
            this.$set(this.item, 'likes', this.item.likes + 1)
            this.$set(this.item, 'liked', true)
          }else {
            this.$set(this.item, 'likes', this.item.likes - 1)
            this.$set(this.item, 'liked', false)
          }
        }
      })
    }
  },
  onLoad(options) {
    this.fid = options.id
    this.getDetail()
    this.getCommentList(false)
    // 浏览5s以上记录浏览次数
    this.timer = setTimeout(() => {
      plusViews(options.id, this.$store.getters.id)
    }, 5 * 1000)
  },
  updated() {
    const dom = uni.createSelectorQuery().in(this).select('.content')
    dom.boundingClientRect((info) => {
      this.multipleSize = (info.width - 50) / 3
    }).exec()
  },
} 
</script>

<style scoped lang="scss">
.content {
  box-sizing: border-box;

  .body {
    background-color: #ffffff;
    padding: 1px 15px 20px;
    box-sizing: border-box;
  }

  .user {
    display: flex;
    align-items: center;
    margin: 20px 0 10px;
  }

  .avatar {
    width: 48px;
    height: 48px;
    margin-right: 10px;

    image {
      width: 100%;
      height: 100%;
      border-radius: 50%;
    }
  }

  .article {
    margin: 10px 0;
  }

  .u-album {
    border-radius: 8px;
    overflow: hidden;
  }

  .album__footer {
    display: flex;
    align-items: center;
    padding-top: 10px;

    view {
      display: flex;
      width: 100%;
      align-items: center;
      justify-content: center;
    }

    image {
      width: 24px;
      height: 24px;
      margin-right: 10px;
    }
  }

  .comments {
    background-color: #ffffff;
  }

  .comment_title {
    padding: 10px 15px;
    background-color: #f5f5f5;
  }

  .content-item {
    margin: 10px 0;
    padding: 0 20px 10px;
    border-bottom: 2px dashed #f5f5f5;
    box-sizing: border-box;
  }

  .comment_content {
    padding-bottom: 1px;
  }

  .user {
    display: flex;
    align-items: center;

    &_avatar {
      width: 48px;
      height: 48px;
      margin-right: 10px;

      image {
        width: 100%;
        height: 100%;
        border-radius: 50%;
      }
    }

    &_info {
      flex: 1;
    }

    &_name {
      display: flex;
      align-items: center;
      padding-top: 5px;
      width: calc(100% - 58px);

      &_label {
        max-width: calc(100% - 10px - 22px);
        margin-right: 10px;
        font-size: 16px;
        font-weight: 600;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
      }

      &_tag {
        background-color: #ccc;
        padding: 1px 5px;
        border-radius: 4px;
        color: #666;
        font-size: 10px;
        line-height: 14px;
        font-weight: bold;
      }
    }

    .comment-property {
      display: flex;
      align-items: center;
      color: #999999;
      font-size: 12px;

      .line {
        display: block;
        width: 1px;
        height: 12px;
        margin: 0 5px;
        background-color: #999999;
      }
    }

    
  }

  .item_content {
    color: #000000;
  }

  .user_ip {
    display: flex;
    padding-top: 5px;
    color: #999999;
    font-size: 12px;

    & > view {
      flex: 1;
    }

    .u-icon {
      display: flex;
      justify-content: flex-end;
    }
  }

  .comment_send {
    position: fixed;
    align-items: flex-end;
    top: 100vh;
    transform: translateY(-100%);
    display: flex;
    width: 100%;
    padding: 10px;
    box-sizing: border-box;
    background-color: #ffffff;
    border-top: 1px solid #eeeeee;

    .button {
      height: 24px;
      padding: 3px 10px;
      background-color: #000000;
      border-radius: 4px;
      color: #ffffff;
      font-size: 12px;
    }
  }
}
</style>